package org.example.lib;


import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.Application;
import org.example.annotations.route.RequestMapping;

import java.io.IOException;

@Slf4j
@WebServlet(value = "/", loadOnStartup = 1)
public class ApplicationHttpServlet extends HttpServlet {

    private final IocContainer iocContainer = IocContainer.instance;
    private final Router router = Router.instance;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        unifiedDo(req, resp, RequestMapping.HttpMethod.GET);
    }

    private void unifiedDo(HttpServletRequest req, HttpServletResponse resp, RequestMapping.HttpMethod method) throws ServletException, IOException {
        resp.setContentType("text/plain");
        Object res = "Not Found";
        int StatusCode = HttpServletResponse.SC_NOT_FOUND;
        Route route = router.findRoute(req.getRequestURI(), method);
        if (route != null) {
            try {
                res = route.invoke(
                        route.getRouteParam(req.getRequestURI()),
                        req,
                        resp
                );
                StatusCode = HttpServletResponse.SC_OK;
            } catch (Exception e) {
                StatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                res = e.getMessage();
                log.error("Http Error", e);
            }
        }
        resp.setStatus(StatusCode);
        resp.getWriter().println(res.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        unifiedDo(req, resp, RequestMapping.HttpMethod.POST);
    }

    @Override
    public void init() {
        log.info("---------- Servlet start ini ----------");
        Application.init();
        iocContainer.buildBeans();
        log.info("---------- Servlet start success ----------");
    }
}
